<template>
  <div class="userAdd">
    <el-dialog v-bind="$attrs" :visible.sync="showDialog" v-on="$listeners" @open="onOpen" @close="onClose" v-dialog-drag title="">
      <el-tabs v-model="activeName" @tab-click="handleClick" >
        <el-tab-pane label="用户信息" name="first" >
          <el-row :gutter="15">
            <el-form ref="elForm" :model="upUserVO" :rules="rules" size="medium" label-width="100px">
              <el-col :span="24">
                <!-- 用户头像 -->
                <el-form-item label="用户头像">

                  <!-- 头衔缩略图 -->
                  <pan-thumb :image="image"/>
                  <!-- 文件上传按钮 -->
                  <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像
                  </el-button>

                  <!--
                    v-show：是否显示上传组件
                    :key：类似于id，如果一个页面多个图片上传控件，可以做区分
                    :url：后台上传的url地址
                    @close：关闭上传组件
                    @crop-upload-success：上传成功后的回调 -->
                  <image-cropper
                    v-show="imagecropperShow"
                    :width="300"
                    :height="300"
                    :key="imagecropperKey"
                    :url="'/aliOss/uploadFile'"
                    field="file"
                    @close="closeImage"
                    @crop-upload-success="cropSuccess"/>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="upUserVO.username" placeholder="请输入用户名" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="upUserVO.nickname" placeholder="请输入昵称" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="upUserVO.password" placeholder="请输入密码" clearable show-password
                            :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phoneNumber">
                  <el-input v-model="upUserVO.phoneNumber" placeholder="请输入手机号" clearable
                            :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门" prop="departmentId">
                  <el-select v-model="upUserVO.departmentId" placeholder="请选择部门" clearable
                             :style="{width: '100%'}">
                    <el-option v-for="(item, index) in departmentIdOptions" :key="index" :label="item.name"
                               :value="item.id" :disabled="item.s"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="upUserVO.sex" size="medium">
                    <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value"
                              :disabled="item.disabled">{{item.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="upUserVO.email" placeholder="请输入邮箱" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
                <el-form-item label="生日" prop="birth">
                  <el-date-picker v-model="upUserVO.birth" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                  :style="{width: '100%'}" placeholder="请选择生日" clearable></el-date-picker>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="角色信息" name="second">
          <!--              <p style="text-align: center; margin: 0 0 20px">使用 render-content 自定义数据项</p>-->
          <el-transfer
            v-model="upUserVO.yesData"
            :props="{key: 'id',label: 'roleName'}"
            :titles="['未关联', '已关联']"
            @change="handleChange"
            :data="upUserVO.noData"
          ></el-transfer>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import  ImageCropper from '../../components/ImageCropper'
import  PanThumb from '../../components/PanThumb'
import {deleteImage} from '@/api/image'
import {saveUser } from '@/api/users'
import {findDicByCateAndKey} from '@/api/dic'
import {findRoleByIds} from '@/api/role'
import {findUnAssignRoleById} from '@/api/role'
import {getRolesByUserName} from '@/api/users'

export default {
  inheritAttrs: false,
  components: {
    ImageCropper,
    PanThumb
  },
  props: {
    updateVisible:{
      type : Boolean,
      default:false
    },
    departmentIdOptions:{
      type : Array,
      default :[]
    },
    updateUserVO:{
      type : Object,
      default :{}
    }
  },
  data() {
    return {
      dic:{
        category:'role_default',
        keyword:'role_id'
      },
      roleIds:[],
      activeName : 'first',
      showDialog:false,
      upUserVO: {
        noData: [],
        yesData:[],
        id:null,
        avatar: null,
        username: '',
        departmentId: undefined,
        nickname: undefined,
        sex: 2,
        password: undefined,
        email: undefined,
        phoneNumber: undefined,
        birth: null,
      },
      imagecropperShow: false, // 是否显示上传组件
      imagecropperKey: 0, // 上传组件id
      image: 'http://xinguan-parent11.oss-cn-beijing.aliyuncs.com/2021/04/10/dc1926488e7e45ada4b9b0ac02643c9a.png',
      rules: {
        username: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        departmentId: [{
          required: true,
          message: '请选择部门',
          trigger: 'change'
        }],
        nickname: [{
          required: true,
          message: '请输入昵称',
          trigger: 'blur'
        }],
        sex: [],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }],
        phoneNumber: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }],
        birth: [{
          required: true,
          message: '请选择生日',
          trigger: 'change'
        }],
      },
      field101Action: 'https://jsonplaceholder.typicode.com/posts/',
      field101fileList: [],
      sexOptions: [{
        "label": "男",
        "value": 0
      }, {
        "label": "女",
        "value": 1
      }, {
        "label": "保密",
        "value": 2
      }],
    }
  },
  computed: {},
  watch: {
    updateVisible:function(){
      //监听updateVisible改变
      this.showDialog = this.updateVisible
    },
    updateUserVO:function(){
      //监听updateUserVO改变
      this.upUserVO.id = this.updateUserVO.id
      this.upUserVO.avatar = this.updateUserVO.avatar
      this.upUserVO.departmentId = this.updateUserVO.departmentId
      this.upUserVO.email = this.updateUserVO.email
      this.upUserVO.nickname = this.updateUserVO.nickname
      this.upUserVO.phoneNumber = this.updateUserVO.phoneNumber
      this.upUserVO.sex = this.updateUserVO.sex
      this.upUserVO.username = this.updateUserVO.username
      this.upUserVO.password = this.updateUserVO.password
      let momentObj = this.moment(this.updateUserVO.birth, 'YYYY-MM-DD');
      let momentString = momentObj.format('YYYY-MM-DD');
      this.upUserVO.birth = momentString
      console.log("250000000000000000")
      console.log("updateUserVO改变watch1")
      this.parentClick(this.upUserVO)
    },
  },
  created() {
  },
  mounted() {},
  methods: {
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys);
      //可以通过direction回调right/left 来进行操作，right：把数字移到右边，left把数据移到左边
      if(direction === "right") {
      }
      if(direction === "left") {
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    onOpen() {},
    onClose() {
      this.$refs['elForm'].resetFields()
      console.log("onClose");
      this.$emit('changeShow','false')
      this.roleIds=[]
      this.upUserVO.noData=[]
      this.upUserVO.yesData=[]
      // this.upUserVO={}
    },
    close() {
      console.log("Close");
      this.$emit('update:visible', false)
      this.$emit('changeShow','false')
      this.roleIds=[]
      this.upUserVO.noData=[]
      this.upUserVO.yesData=[]
      // this.upUserVO={}
    },
    handelConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) {
          return
        }
        console.log(this.upUserVO)
        this.assUser();
      })
    },
    async assUser(){
      console.log(this.upUserVO.yesData)
      const {data : res} = await saveUser(this.upUserVO);
      console.log(res)
      if(res.code == 200){
        this.$emit('changeShow','false')
        this.upUserVO = {}
        this.$notify.success({
          title:'操作成功',
          message:'用户操作成功'
        })
      }else{
        return this.$message.error('用户操作失败:'+ res.msg)
      }
    },
    field101BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    //弹窗后触发
    handleClose(){
      //子组件调用父组件方法，并传递参数
      this.$emit('changeShow','false')
    },
    // 上传成功后的回调函数
    cropSuccess (data) {
      let oldImage = this.image;
      //使用该属性保存上传之前的图片
      this.imagecropperShow = false
      this.upUserVO.avatar = this.image = data.msg
      // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1
      //上传头像成功后  删除之前的头像
      this.deleteAvater(oldImage)
    },
    // 关闭上传组件
    closeImage () {
      this.imagecropperShow = false
      // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1
    },
    async deleteAvater(oldImage){
      const {data} = await deleteImage(oldImage)
      console.log(data)
    },
    parentClick(a){
      //根据点击的用户名称  查询用户拥有的角色
      console.log("updateUserVO改变")
      getRolesByUserName(a.username).then(res =>{
        console.log(res.data.data.roleListYes)
        let roleListYes = res.data.data.roleListYes
        if(roleListYes != null && roleListYes.length > 0){
          roleListYes.map((item)=>
            this.roleIds.push(item.id)
            )
        }
        console.log(this.roleIds)
        findRoleByIds(this.roleIds).then(res => {
          console.log(res)
          console.log("res")
          if(res.data.data != null && res.data.data.length > 0){
            for(let i in res.data.data){
              this.upUserVO.yesData.push(
                res.data.data[i].id
              )
              this.upUserVO.noData.push(
                res.data.data[i]
              )
            }
          }
        })
        //查询除了未赋予的角色
        console.log("根据拥有的角色id查询未赋予的角色");
        findUnAssignRoleById(this.roleIds).then(res => {
          console.log("sdfsdfsf")
          console.log(res)
          if(res.data.data != null && res.data.data.length > 0){
            for(let i in res.data.data){
              this.upUserVO.noData.push(
                res.data.data[i]
              )
            }
            console.log(this.upUserVO.yesData)
            console.log(this.upUserVO.noData)
          }
        })
      })
    }
  }
}

</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 500px;
  display: block;
}
.el-dialog__body{
  height: 450px;
  width: 700px;
}
.transfer-footer {
  margin-left: 20px;
  padding: 6px 5px;
}
</style>
